package service

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/share309/gojwt"
	"service/basic/config"
	__ "service/basic/proto"
	"service/handler/model"
	"time"
)

type Server struct {
	__.UnimplementedClassServer
}

func (s *Server) Logion(_ context.Context, in *__.LogionReq) (*__.LogionResp, error) {
	var user model.User
	user.Mobile = in.Mobile
	user.Password = in.Password
	if user.Password != in.Password {
		return nil, errors.New("密码错误")
	}
	//生成token
	token, err := gojwt.NewJWT("2301a").CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 3600,
		},
	})
	if err != nil {
		return nil, errors.New("登录失败")
	}
	marshal, _ := json.Marshal(&token)
	config.Rdb.Set(config.Ctx, "token"+in.Mobile, marshal, time.Hour)

	return &__.LogionResp{
		Token: token,
	}, nil
}

func (s *Server) Home(_ context.Context, in *__.HomeReq) (*__.HomeResp, error) {
	var home model.Home
	homeList, err := home.List()
	if err != nil {
		return nil, errors.New("首页列表展示失败")
	}

	var homeLists []*__.HomeList
	for _, h := range homeList {
		list := __.HomeList{Module: h.Module}
		homeLists = append(homeLists, &list)
	}
	jsonData, _ := json.Marshal(&homeList)
	config.Rdb.Set(config.Ctx, "module_list", jsonData, time.Hour)

	return &__.HomeResp{
		List: homeLists,
	}, nil
}

func (s *Server) Like(_ context.Context, in *__.LikeReq) (*__.LikeResp, error) {
	var like model.Like
	like.UserId = uint32(in.UserId)
	like.ClassId = uint32(in.ClassId)
	if err := like.GetUserId(); err != nil {
		return nil, errors.New("用户id查找失败")
	}
	var class model.Class
	if err := class.Detail(); err != nil {
		return nil, errors.New("id查找失败")
	}

	return &__.LikeResp{
		Id:       int64(class.Id),
		Title:    class.Title,
		Info:     class.Info,
		CoverUrl: class.CoverUrl,
		VideoUrl: class.VideoUrl,
		VipPrice: float32(class.VipPrice),
		Price:    float32(class.Price),
		TypesId:  int64(class.TypesId),
	}, nil
}
